package com.restaurant.application.start;

import com.nebutown.commonunits.utils.QiNiuUtil;
import com.nebutown.generation.Convert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ImageToken extends HttpServlet {
    private static final Logger LOG = LoggerFactory.getLogger(ImageToken.class);

    /**
     *
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    /**
     *
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     *
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        LOG.debug("======get token servlet======");
        String token = QiNiuUtil.getSimpleUploadToken();
        writePage(response, Convert.toJson(token));
    }

    public static void writePage(HttpServletResponse response, String content) {
        try {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
            response.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
            response.setContentType("text/html;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            if (LOG.isTraceEnabled()) {
                LOG.trace("writing: {}", content);
            } else {
                LOG.debug("writing: {}", content);
            }
            response.getWriter().write(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
